package com.lfsenior.jms;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by dlupan on 2018/10/31
 */
public class MessageReceiver {
    public static void run() throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        // 创建连接
        Connection connection = factory.createConnection();
        // 启动连接
        connection.start();
        // 创建session会话
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        // 创建一个消息队列（目的地）
        Destination queue = session.createQueue("JMS-QUEUE");
        // 创建消息消费者
        MessageConsumer consumer = session.createConsumer(queue);
        while (true) {
            // 接收数据的时间（等待）1000s
            Message message = consumer.receive(1000);

            TextMessage text = (TextMessage) message;
            if (text != null) {
                System.out.println("接收：" + text.getText());
            } else {
                break;
            }
        }
        //提交会话
        session.commit();
        session.close();
        connection.close();
    }

    public static void main(String[] args) throws Exception{
        MessageReceiver.run();
    }
}
